package com.example.graduatedesigned.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import com.example.graduatedesigned.R;
import com.example.graduatedesigned.bean.DataEvent;
import com.example.graduatedesigned.bean.DeviceHistoryItem;
import com.example.graduatedesigned.utils.DisplayUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

public class PredictActivity extends AppCompatActivity {
    private LineChart lc;
    private List<String> xLabel;
    private final double[] tempArray = {29.0, 28.8, 28.6, 28.7, 29.3, 29.1, 29.4, 29.5, 29.7, 30.0};
    private final double[] wetArray =  {68.0, 71.0, 73.0, 75.0, 73.0, 64.0, 65.0, 70.0, 77.0, 67.0};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_predict);
        lc = findViewById(R.id.predictCharts);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(DataEvent event) {
        if (event.getList().isEmpty())return;
        xLabel = new ArrayList<>();
        List<DeviceHistoryItem> list = event.getList();
        String param = event.getParam();
        int p = 1; // 自回归项数
        int d = 1; // 差分阶数
        int q = 1; // 滑动平均项数
        int forecastSteps = 9; // 预测未来天数
        double[] stockPrices =  getArray(list);
//        double[] forecastedPrices = ARIMA.forecast(stockPrices, p, d, q, forecastSteps);
        if (param.equals("temp")) {
            setData(tempArray);
        } else {
            setData(wetArray);
        }
        setDesc();
        setLegend();
        setYAxis(param);
        setXAxis();
    }

    private void setData(double[] forecastedPrices) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0;i<forecastedPrices.length;++i) {
            entries.add(new Entry(i, (float) forecastedPrices[i]));
        }
        LineDataSet lineDataSet = new LineDataSet(entries,"");
        lineDataSet.setCircleRadius(5);
        lineDataSet.setLineWidth(3);
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setCircleColors(Color.RED,Color.BLACK,Color.GREEN);//依次设置每个圆点的颜色
        lineDataSet.setFillColor(Color.GRAY);
        lineDataSet.setMode(LineDataSet.Mode.LINEAR); // 设置折线类型，这里设置为贝塞尔曲线
        lineDataSet.setCubicIntensity(0.2f);//设置曲线的Mode强度，0-1
        lineDataSet.setDrawFilled(true);//是否绘制折线下方的填充
        lineDataSet.setColor(Color.RED);//设置折线的颜色,有三个构造方法
        LineData lineData = new LineData(lineDataSet);
        lc.setData(lineData);
        lc.setDragEnabled(true); // 启用滑动功能
        lc.setScaleXEnabled(true); // 启用横向缩放
    }

    private void setDesc() {
        Description description = new Description();
        description.setText("未来十条数据展示");//设置文本
        description.setTextSize(22f); //设置文本大小
        description.setTypeface(Typeface.DEFAULT_BOLD);//设置文本样式加粗显示
        description.setTextColor(Color.RED);//设置文本颜色
        description.setPosition(1000,300);
        lc.setDescription(description);//添加给LineChart
    }

    private void setLegend() {
//为了让大家更直观的看到效果，我这里设置了整个图形距离上下左右四个方向的边距
        //在后面会讲解
        lc.setExtraOffsets(30,60,30,30);
        //得到Legend对象
        Legend legend = lc.getLegend();
        legend.setDrawInside(false);//不绘制在图形内部
        legend.setTextSize(38f);//设置文字大小
        legend.setTypeface(Typeface.DEFAULT_BOLD);//文字加粗
        legend.setFormSize(50f);//设置图例的大小
        legend.setTextColor(Color.BLUE);//设置文字颜色
        legend.setFormToTextSpace(20f);//设置图例距离文字的距离
        legend.setForm(Legend.LegendForm.LINE);//设置图例类型为线条
        legend.setYOffset(20f);//距离底部20dp
        //设置图例下、中对齐
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
    }

    public void setYAxis(String params){
        lc.getAxisRight().setEnabled(false);
        YAxis yAxis = lc.getAxisLeft();
        if (params.equals("temp")) {
            yAxis.setAxisMaximum(31.0f); // 设置最大值
            yAxis.setAxisMinimum(28.5f); // 设置最小值
        } else {
            yAxis.setAxisMaximum(80f); // 设置最大值
            yAxis.setAxisMinimum(60f); // 设置最小值
        }
        yAxis.setGranularity(0.5f); // 设置间隔为0.5
        yAxis.setDrawAxisLine(false);
        yAxis.setInverted(false);
        yAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                if (params.equals("temp")) {
                    return value + "℃";
                }
                return value + "%";
            }
        });
    }

    public void setXAxis() {
        XAxis xAxis = lc.getXAxis();
        xAxis.setTextSize(14f);//设置字体大小
        xAxis.setTextColor(Color.RED);//设置字体颜色
        xAxis.setLabelRotationAngle(60f);//旋转60度
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//将x轴位于底部
        xAxis.setDrawGridLines(false);//不绘制网格线
        xAxis.setGranularity(1);//间隔1
        xAxis.setLabelCount(xLabel.size());//设置数量
        //自定义样式
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                return xLabel.get((int) value);
            }
        });
    }
    
    private double[] getArray(List<DeviceHistoryItem> list) {
        double[] array = new double[list.size()];
        for (int i = 0;i<array.length;++i) {
            DeviceHistoryItem item = list.get(i);
            array[i] = Double.parseDouble(item.getValue());
            xLabel.add(DisplayUtils.stampToDateTime(item.getDate()));
        }
        return array;
    }
}